package com.cn.rpcframe.network;

import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;

import com.cn.rpcframe.entity.ClassInfo;
import com.cn.rpcframe.utils.SerializeUtils;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class InvokerHandler extends ChannelInboundHandlerAdapter {
	 
	 public InvokerHandler(ConcurrentHashMap classMap ){
		 this.serviceRegistry=classMap;
	 }
	 
	 @Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		// TODO Auto-generated method stub
		cause.printStackTrace();
		ctx.close();
		super.exceptionCaught(ctx, cause);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		// TODO Auto-generated method stub
		 
		  ClassInfo classInfo = (ClassInfo)msg;
		  Class claszz = null;  
		  if(!serviceRegistry.containsKey(classInfo.getClassName())){
			  try {  
	                claszz = (Class) Class.forName(classInfo.getClassName()).newInstance();  
	                serviceRegistry.put(classInfo.getClassName(), claszz.getClass());  
	            } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {  
	                e.printStackTrace();  
	            }  
		  }else{
			  claszz = serviceRegistry.get(classInfo.getClassName());  
		  }
		  Method method = claszz.getMethod(classInfo.getMethodName(), classInfo.getTypes());    
	        Object result = method.invoke(claszz.newInstance(), classInfo.getObjects());   
	       
	        ctx.write(result);  
	        ctx.flush();    
	        ctx.close();
		 
	}

	  private static   ConcurrentHashMap<String, Class> serviceRegistry;

}
